import {WeaTools} from "ecCom";
import * as types from "../constants/ActionTypes";
import * as urls from "../constants/ServerUrls";

const {callApi} = WeaTools;

/**
 * 加载目录树
 * @param parentId
 * @returns {function(*)}
 */
export const loadTree = parentId => {
    return dispatch => {
        let treeurl = urls.LOAD_TREE_URL;
        callApi(treeurl, "POST", {parentId}).then(resdata => {
            let msg = resdata.msg;
            let success = resdata.success;
            if (success == "1") {
                let data = resdata.data;
                dispatch(setTreeData(data, parentId, success, msg));

                //加载数据完成后，再打开收藏目录窗口，避免窗口打开后，可以看到数据修改的过程
                dispatch(showOrHideSpinning(false));
            }
        });
    }
}

/**
 * 关闭窗口时调用，清空数据
 * @returns {{type}}
 */
export const destroyBrowser = () => {
    return {
        type: types.FAVBROWSER_CLEAR_DATA
    };
}


/**
 * 节点选中
 * @param selectedKey
 * @returns {function(*): *}
 */
export const selectTreeNode = selectedKey => {
    return {
        type: types.FAVBROWSER_SELECT_DIR,
        selectedKey
    };
}

/**
 * 添加树节点
 * @param selectedKey
 * @returns {{type, selectedKey: *}}
 */
export const addTreeNode = selectedKey => {
    return {
        type: types.FAVBROWSER_ADD_DIR,
        selectedKey
    };
}

/**
 * 保存树节点
 * @param params
 */
export const saveTreeNode = (params) => {
    let favurl = urls.SAVE_FAVOURITE_DIR;
    let {parentid} = params;
    return dispatch => {
        callApi(favurl, "POST", {...params}).then(resdata => {
            let success = resdata.success;
            let msg = "";
            if (success == "0") {
                msg = resdata.msg;
            }

            //错误处理
            dispatch({
                type: types.MYFAV_RESULT_SET,
                success,
                msg
            });

            dispatch(loadTree(parentid));  //刷新父节点
        });
    }
}

/**
 * 显示加载中的遮罩
 * @param spinning
 * @param tip
 * @returns {{type, spinning: *, tip: string}}
 */
export const showOrHideSpinning = (spinning, tip = "") => {
    return {
        type: types.FAVBROWSER_SHOW_OR_HIDE_SPINNING,
        spinning,
        tip
    }
}

function setTreeData(data, parentId) {
    return {
        type: types.FAVBROWSER_LOAD_TREE,
        treeData: data,
        parentId
    };
}

